﻿using Shop.Model.DB;
using Shop.Model.Shop;
using Shop.Repository;
using WeDonekRpc.CacheClient.Interface;
using WeDonekRpc.Client;

namespace Shop.Collect.lmpl
{
    internal class ShopCollect : IShopCollect
    {
        private readonly IShopRepository _Repository;
        private readonly ICacheController _Cache;
        public ShopCollect (IShopRepository repository, ICacheController cache)
        {
            this._Cache = cache;
            this._Repository = repository;
        }
        public Result Get<Result> (long id) where Result : class
        {
            return this._Repository.Get<Result>(id);
        }
        public DBShop Get (long id)
        {
            return this._Repository.Get(id);
        }
        public bool Set (DBShop shop, ShopSet set)
        {
            return this._Repository.Update(shop, set);
        }
        public long Add (ShopAdd add)
        {
            DBShop shop = add.ConvertMap<ShopAdd, DBShop>();
            this._Repository.Add(shop);
            string key = "ComShopId_" + add.CompanyId;
            _ = this._Cache.Remove(key);
            return shop.Id;
        }

        public long GetByCompanyId (long companyId)
        {
            string key = "ComShopId_" + companyId;
            if (this._Cache.TryGet(key, out long id))
            {
                return id;
            }
            id = this._Repository.Get(a => a.CompanyId == companyId, a => a.Id);
            _ = this._Cache.Set(key, id);
            return id;
        }
    }
}
